/******************************************************************
*
* CyberUPnP for Java
*
* Copyright (C) Satoshi Konno 2002-2003
*
* File: HTTPServerList.java
*
* Revision;
*
* 05/08/03
*   - first revision.
*
******************************************************************/

package com.cidero.http;

import java.util.*;
import java.util.logging.Logger;

public class HTTPServerList extends Vector 
{
  private static Logger logger = Logger.getLogger("com.cidero.http");

  ////////////////////////////////////////////////
  //  Constructor
  ////////////////////////////////////////////////
  
  public HTTPServerList() 
  {
  }

  ////////////////////////////////////////////////
  //  Methods
  ////////////////////////////////////////////////

  public void addRequestListener(HTTPRequestListener listener)
  {
    int nServers = size();
    for (int n=0; n<nServers; n++) {
      HTTPServer server = getHTTPServer(n);
      server.addRequestListener(listener);
    }
  }   
  
  public HTTPServer getHTTPServer(int n)
  {
    return (HTTPServer)get(n);
  }

  ////////////////////////////////////////////////
  //  open/close
  ////////////////////////////////////////////////

  public void close()
  {
    int nServers = size();
    for (int n=0; n<nServers; n++) {
      HTTPServer server = getHTTPServer(n);
      server.close();
    }
  }

  /**
   *  Attempt to open a server instance for each host interface. If 
   *  interface present, but not bound, it is not added to the server list
   *  (thanks to Greg Johnson for patch)
   *
   *  @param port  Port to open server on 
   *
   *  @return true if at least one server instance was started, otherwise
   *  false
   */
  public boolean open(int port) 
  {
    int nHostAddrs = HostInterface.getNHostAddresses();

    clear();

    for (int n=0; n<nHostAddrs; n++)
    {
      String bindAddr = HostInterface.getHostAddress(n);
      HTTPServer httpServer = new HTTPServer();
      if( httpServer.open(bindAddr, port) == true )
      {
        add(httpServer);
      }
      else
      {
        logger.warning("Failed to bind HTTP server at addr: " + bindAddr 
                       + " port: " + port );
      }
    }

    if( size() > 0 )
      return true;
    else
      return false;
  }
  
  ////////////////////////////////////////////////
  //  start/stop
  ////////////////////////////////////////////////
  
  public void start()
  {
    int nServers = size();
    for (int n=0; n<nServers; n++) {
      HTTPServer server = getHTTPServer(n);
      server.start();
    }
  }

  public void stop()
  {
    int nServers = size();
    for (int n=0; n<nServers; n++) {
      HTTPServer server = getHTTPServer(n);
      server.stop();
    }
  }

}

